package interfaz;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;

/**
 *
 * @author victor
 */
public class iPicture extends iWidget {
    private String path;
    private Canvas canvas;
    private ImageBuffer buffer = null;
    private int border = 0; /* Borde da imaxe */
    private Color borderColor = Color.WHITE;
    
    /** Creates a new instance of iPicture */
    public iPicture(int x, int y) {
        super(x,y);
    }
    
    public void setImage(String path) {
        this.path = path;
    }
    
    public void loadBuffer() {
        if (buffer == null) {
            refreshBuffer();
        }
    }
    
    public void refreshBuffer() {
            buffer = new ImageBuffer(path);
            buffer.run();
    }
    
    public void setBorder(int border) {
        this.border = border;
    }
    
    public int getBorder() {
        return border;
    }
    
    public String getPath() {
        return path;
    }
    
    public void setCanvas(Canvas canvas) {
        this.canvas = canvas;
    }
    
    public void setBorderColor(Color color) {
        this.borderColor = color;
    }
    
    public Color getBorderColor() {
        return this.borderColor;
    }
    
    public void paint(Graphics g) {
        if (buffer == null) loadBuffer();
        g.setColor(getBorderColor());
        if (getBorder() > 0)
            g.fillRect(getX()-getBorder(),getY()-getBorder(),
                    getWidth()+getBorder()*2,getHeight()+getBorder()*2);
        g.drawImage(buffer.getBuffer(),getX(),getY(),getWidth(),getHeight(),this.canvas);
    }
    
    public void setRealSize() {
        if (buffer == null) loadBuffer();
        setHeight(buffer.getBuffer().getHeight());
        setWidth(buffer.getBuffer().getWidth());
    }
    
    public void setAdjustedSize(int width, int height) {
        float ratio = 1;

        if (buffer == null) {
            loadBuffer();
        }
        if ((buffer.getBuffer().getWidth() >= width - 100) ||
                (buffer.getBuffer().getHeight() >= height - 100)) {
            if (buffer.getBuffer().getWidth()  
                    > buffer.getBuffer().getHeight()) { /* Foto apaisada */
                ratio = (float) (height-100) / buffer.getBuffer().getHeight();
            } 
            else if (buffer.getBuffer().getHeight() 
                    >= buffer.getBuffer().getHeight()) { /* Foto vertical ou 
                                                        cadrada */ 
                ratio = (float) (width-100) / buffer.getBuffer().getWidth();

            }
            
            float newWidth =
                    (float) (buffer.getBuffer().getWidth()) * ratio;
            float newHeight =
                    (float) (buffer.getBuffer().getHeight()) * ratio;
            setWidth((int) newWidth);
            setHeight((int) newHeight);
        }
        else setRealSize();
    }
}
